package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.BaseException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import io.swagger.util.Json;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    AddressBookMapper addressBookMapper;
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    WeChatPayUtil weChatPayUtil;
    @Autowired
    UserMapper userMapper;
    @Autowired
    WebSocketServer webSocketServer;

    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        //处理业务异常（地址簿为空，购物车为空）
        //判断地址簿是否为空
        AddressBook add = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(add==null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //判断购物车是否为空
        Long userId = BaseContext.getCurrentId();
        ShoppingCart cart = ShoppingCart.builder().userId(userId).build();
        List<ShoppingCart> list = shoppingCartMapper.list(cart);
        if(list==null||list.isEmpty()){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //向订单表插入1条数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setOrderTime(LocalDateTime.now());
        order.setPayStatus(Orders.UN_PAID);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setNumber(Long.toString(System.currentTimeMillis()));
        order.setPhone(add.getPhone());
        order.setConsignee(add.getConsignee());
        order.setUserId(userId);
        order.setAddress(add.getDetail());

        orderMapper.insert(order);
        //向订单明细表插入n条数据
        List<OrderDetail> details = new ArrayList<>();
        for (ShoppingCart cartL : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cartL, orderDetail);
            orderDetail.setOrderId(order.getId());
            details.add(orderDetail);
        }
        //批量插入订单明细
        orderDetailMapper.insertBatch(details);
        //清空用户的购物车数据
        shoppingCartMapper.deleteByUserId(userId);
        //封装vo返回结果
        OrderSubmitVO result = OrderSubmitVO.builder()
                .id(order.getId())
                .orderTime(order.getOrderTime())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .build();
        return result;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //通过websocket向客户端浏览器推消息
        Map map = new HashMap<>();
        map.put("type","1");
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号："+outTradeNo);
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    @Override
    public PageResult orderPageWithDetail(OrdersPageQueryDTO dto) {
        //查询订单
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Long userId = BaseContext.getCurrentId();
        dto.setUserId(BaseContext.getCurrentId());
        Page<OrderVO> page = orderMapper.pageQuery(dto);
        if(page==null||page.isEmpty()){
            return null;
        }
        List<OrderVO> orders = page.getResult();
        //查询订单详情
        for (OrderVO order : orders) {
            List<OrderDetail>details = orderDetailMapper.getByOrderId(order.getId());
            order.setOrderDetailList(details);
        }
        //封装数据
        PageResult result = new PageResult();
        result.setTotal(page.getTotal());
        result.setRecords(orders);
        return result;
    }

    @Override
    public OrderVO getOrderWithDetail(Long id) {
        OrderVO result = orderMapper.getById(id);
        List<OrderDetail> details = orderDetailMapper.getByOrderId(id);
        result.setOrderDetailList(details);
        return result;
    }

    @Override
    public void userCancelOrder(Long id) {
        Orders update = new Orders();
        //检查订单状态
        OrderVO target = orderMapper.getById(id);
        if(target==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Integer status = target.getStatus();
        if(status>2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //是否需要退款
        if(status==2){
            try {
                weChatPayUtil.refund(target.getNumber(),target.getNumber(),
                        BigDecimal.valueOf(0.01),BigDecimal.valueOf(0.01));
            } catch (Exception e) {
                throw new BaseException("退款失败");
            }
            update.setPayStatus(Orders.REFUND);
        }
        //更新订单取消原因和取消时间
        update.setId(id);
        update.setStatus(Orders.CANCELLED);
        update.setCancelTime(LocalDateTime.now());
        update.setCancelReason("用户取消");
        orderMapper.update(update);
    }

    @Override
    public void addShoppingCartByOderId(Long id) {
        //查询OrderDetail
        List<OrderDetail> details = orderDetailMapper.getByOrderId(id);
        //添加购物车
        if(details==null||details.isEmpty()){
            return;
        }
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> carts = new ArrayList<>();
        for (OrderDetail detail : details) {
            ShoppingCart cart = new ShoppingCart();
            BeanUtils.copyProperties(detail,cart);
            cart.setUserId(userId);
            cart.setCreateTime(LocalDateTime.now());
            carts.add(cart);
        }
        shoppingCartMapper.insertBatch(carts);
    }

    @Override
    public PageResult adminPage(OrdersPageQueryDTO dto) {
        //改造：details=>(string)orderDish
        //查询订单
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page<OrderVO> page = orderMapper.pageQuery(dto);
        if(page==null||page.isEmpty()){
            return new PageResult(0, new ArrayList<>());
        }
        List<OrderVO> orders = page.getResult();
        //查询订单详情
        for (OrderVO order : orders) {
            List<OrderDetail>details = orderDetailMapper.getByOrderId(order.getId());
            //拼接订单商品一览字符串：商品名*数量;...
            if(details==null||details.isEmpty()){
                continue;
            }
            List<String> goods = details.stream().map(o->o.getName()+"*"+o.getNumber()).collect(Collectors.toList());
            String stringGoods = String.join(";", goods);
            order.setOrderDishes(stringGoods);
        }
        //封装数据
        PageResult result = new PageResult();
        result.setTotal(page.getTotal());
        result.setRecords(orders);
        return result;
    }

    @Override
    public OrderStatisticsVO eachStatus() {
        OrderStatisticsVO result = new OrderStatisticsVO();
        result.setConfirmed(orderMapper.countByStatus(Orders.CONFIRMED));
        result.setToBeConfirmed(orderMapper.countByStatus(Orders.TO_BE_CONFIRMED));
        result.setDeliveryInProgress(orderMapper.countByStatus(Orders.DELIVERY_IN_PROGRESS));
        return result;
    }

    @Override
    public void confirmWithCheckStatus(OrdersConfirmDTO dto) {
        OrderVO target = orderMapper.getById(dto.getId());
        if(target==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if(!Objects.equals(target.getStatus(),Orders.TO_BE_CONFIRMED)||
                !Objects.equals(target.getPayStatus(),Orders.PAID)){
            throw new BaseException("订单状态错误");
        }
        Orders update = new Orders();
        update.setId(dto.getId());
        update.setStatus(Orders.CONFIRMED);
        orderMapper.update(update);
    }

    @Override
    public void rejection(OrdersRejectionDTO dto) {
        OrderVO target = orderMapper.getById(dto.getId());
        Orders update = new Orders();
        if(target==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Integer status = target.getStatus();
        if(!Objects.equals(Orders.TO_BE_CONFIRMED, status)){
            throw new OrderBusinessException("订单状态错误");
        }
        update.setId(dto.getId());
        if(Objects.equals(target.getPayStatus(),Orders.PAID)){
            //退款逻辑
            try {
                weChatPayUtil.refund(target.getNumber(),target.getNumber(),BigDecimal.valueOf(0.01),BigDecimal.valueOf(0.01));
            } catch (Exception e) {
                throw new OrderBusinessException("退款失败");
            }
            //修改支付状态为退款
            update.setPayStatus(Orders.REFUND);
        }
        update.setStatus(Orders.CANCELLED);
        update.setRejectionReason(dto.getRejectionReason());
        update.setCancelTime(LocalDateTime.now());
        orderMapper.update(update);
    }

    @Override
    public void adminCancel(OrdersCancelDTO dto) {
        OrderVO target = orderMapper.getById(dto.getId());
        if(target==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Orders update = new Orders();
        update.setId(dto.getId());

        if(Objects.equals(target.getPayStatus(),Orders.PAID)){
            try {
                weChatPayUtil.refund(target.getNumber(),target.getNumber(), BigDecimal.valueOf(0.01), BigDecimal.valueOf(0.01));
            } catch (Exception e) {
                throw new OrderBusinessException("退款失败");
            }
            update.setPayStatus(Orders.REFUND);
        }

        update.setStatus(Orders.CANCELLED);
        update.setCancelReason(dto.getCancelReason());
        update.setCancelTime(LocalDateTime.now());
        orderMapper.update(update);
    }

    @Override
    public void delivery(Long id) {
        OrderVO target = orderMapper.getById(id);
        if(target==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if(!Objects.equals(Orders.CONFIRMED,target.getStatus())){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders update = new Orders();
        update.setId(id);
        update.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(update);
    }

    @Override
    public void complete(Long id) {
        OrderVO target = orderMapper.getById(id);
        if(target==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if(!Objects.equals(Orders.DELIVERY_IN_PROGRESS,target.getStatus())){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders update = new Orders();
        update.setId(id);
        update.setStatus(Orders.COMPLETED);
        update.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(update);
    }

    @Override
    public void reminder(Long id) {
        OrderVO target = orderMapper.getById(id);
        if(target==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        HashMap map = new HashMap();
        map.put("orderId",id);
        map.put("type",2);      //2:客户催单
        map.put("content","订单号："+target.getNumber());
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    @Override
    public OrderReportVO orderReport(LocalDate begin, LocalDate end) {

        //获得日期集合
        List<LocalDate> dateList = new ArrayList<>();
        for(;begin.isBefore(end.plusDays(1));begin=begin.plusDays(1)){
            dateList.add(begin);
        }

        //返回结果
        OrderReportVO result = new OrderReportVO();

        //遍历日期集合，计算每天完成订单数、每天订单总数
        List<Integer>completeList = new ArrayList<>();
        List<Integer>allList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status",Orders.COMPLETED);
            Integer complete = orderMapper.countByTimeAndStatus(map);
            completeList.add(complete);
            map.put("status",null);
            Integer all = orderMapper.countByTimeAndStatus(map);
            allList.add(all);
        }

        //将LocalDate转换为LocalDateTime
        //注意默认转换为00:00:00,故只需转换endDate为当天23:59:59
        Map map = new HashMap();
        map.put("begin", dateList.get(0));
        LocalDate endDate = dateList.get(dateList.size() - 1);
        LocalDateTime endDateTime = LocalDateTime.of(endDate, LocalTime.MAX);
        map.put("end", endDateTime);

        //获得期间订单总数
        Integer all = orderMapper.countByTimeAndStatus(map);

        map.put("status",Orders.COMPLETED);

        //获得期间完成订单总数
        Integer complete = orderMapper.countByTimeAndStatus(map);

        //计算完成率
        Double rate = all==0? 0 : complete * 1.0 / all;

        //构造返回数据
        result.setDateList(StringUtils.join(dateList,','));
        result.setOrderCountList(StringUtils.join(allList,','));
        result.setValidOrderCountList(StringUtils.join(completeList,','));
        result.setValidOrderCount(complete);
        result.setTotalOrderCount(all);
        result.setOrderCompletionRate(rate);
        return result;
    }
}
